package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.sampling;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.WeightPicturesSamplingBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.sampling.SamplingBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.weightSheets.WeightSheetsBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CWeightPicturesSampling;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightPicturesSamplingMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.CAshGateVideoBindServiceImpl;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.TCoalYardAreaServiceImpl;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.timerTasks.ToEamSystem;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.AshGateBindCoalYardVo;
import com.xiaoxu.intranetweb.util.SzResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/sampling")
public class SamplingController {
    @Autowired
    private SamplingBu samplingBu;
    @Autowired
    private CAshGateVideoBindServiceImpl ashGateVideoBindService;
    @Autowired
    private TCoalYardAreaServiceImpl coalYardAreaService;
    @Autowired
    private WeightSheetsBu weightSheetsBu;
    @Autowired
    private CWeightPicturesSamplingMapper cWeightPicturesSamplingMapper;
    @Autowired
    private ToEamSystem toEamSystem;

    // 最大视频大小（300MB）
    private static final long MAX_VIDEO_SIZE = 314572800L;
//    入厂确认
    @PostMapping("/enterConfirm")
    public SzResult enterConfirm(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userId = StpUtil.getLoginIdByToken(token).toString();
        String plantId = request.getHeader("Plant-Id");
//        煤场区域id
        String coalYardAreaId = jsonObject.getString("coalYardAreaId");
//        单号
        String weightSheetNo = jsonObject.getString("weightSheetNo");
        return samplingBu.enterConfirm(coalYardAreaId,weightSheetNo,userId,null);
    }

//    出厂确认
    @PostMapping("/outConfirm")
    public SzResult outConfirm(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String userId = StpUtil.getLoginIdByToken(token).toString();
//        单号
        String weightSheetNo = jsonObject.getString("weightSheetNo");

        return       samplingBu.outConfirm( weightSheetNo,userId,null);
    }
    //    卸车确认
    @PostMapping("/unloadConfirm")
    public SzResult unloadConfirm(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String userId = StpUtil.getLoginIdByToken(token).toString();
//        单号
        String weightSheetNo = jsonObject.getString("weightSheetNo");

        return samplingBu.unloadConfirm( weightSheetNo,null);
    }
//    拿到入厂信息
    @PostMapping("/getEntryData")
    public SzResult getEnterConfirm(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
//

//        单号
        String weightSheetNo = jsonObject.getString("weightSheetNo");
    List<AshGateBindCoalYardVo> coalFields =    coalYardAreaService.getAshGateBindCoalList();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("weightSheetNo",weightSheetNo);
//             document.getElementById('cardNumber').innerText = data.cardNumber;
//        document.getElementById('carNumber').innerText = data.carNumber;
//        document.getElementById('carNumber2').innerText = data.carNumber2;
//        document.getElementById('samplingCode').innerText = data.samplingCode;
//        document.getElementById('entryTime').innerText = new Date(data.entryTime).toLocaleString();
//        document.getElementById('netWeight').innerText = data.netWeight;
        jsonObject1.put("cardNumber","carNumber");
        jsonObject1.put("carNumber","carNumber");
        jsonObject1.put("carNumber2","carNumber2");
        jsonObject1.put("samplingCode","samplingCode");
        jsonObject1.put("entryTime","entryTime");
        jsonObject1.put("netWeight","netWeight");
        jsonObject1.put("coalFields",coalFields);
        jsonObject1.put("pdtNameEntry","pdtNameEntry");
        jsonObject1.put("pdtName","pdtName");
        jsonObject1.put("planNo","2");
        jsonObject1.put("statusExit","statusExit");
//        areas
        jsonObject1.put("area_code_display","1,2,3,4");
        return SzResult.success(jsonObject1);
    }
//    拿到用户、单位、品种信息
    @PostMapping("/getUserAndCpyAndPdt")
    public SzResult getVarietyAndUnit(@RequestBody JSONObject jsonObject) {

        String accessKey = jsonObject.getString("accessKey");
        if (accessKey == null || !accessKey.equals("741852963.+-")){
            return SzResult.Error("密钥不正确");
        }else {
            return samplingBu.getUserAndCpyAndPdt();
        }
    }
//    最终提交接口
    @PostMapping("/submit")
    public SzResult submit(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        try{
        String accessKey = jsonObject.getString("accessKey");
        if (accessKey == null || !accessKey.equals("741852963.+-")){
            return SzResult.Error("密钥不正确");
        }else {
            String weightSheetNo = jsonObject.getString("weightSheetNo");
            String enterTime = jsonObject.getString("enterTime");
            String outTime = jsonObject.getString("outTime");
            String enterUserId = jsonObject.getString("enterUserId");
            String outUserId = jsonObject.getString("outUserId");
            //        煤场区域id
            String coalYardAreaId = jsonObject.getString("coalYardAreaId");
            WeightPicturesSamplingBo weightPicturesSamplingBo = new WeightPicturesSamplingBo();
            weightPicturesSamplingBo.setWeipicSheetno(weightSheetNo);
            weightPicturesSamplingBo.setWeipicSamp1(jsonObject.getString("weipicSamp1"));
            weightPicturesSamplingBo.setWeipicSamp2(jsonObject.getString("weipicSamp2"));
            weightPicturesSamplingBo.setWeipicSamp3(jsonObject.getString("weipicSamp3"));
            weightPicturesSamplingBo.setWeipicSamp4(jsonObject.getString("weipicSamp4"));
            weightPicturesSamplingBo.setWeipicSamp5(jsonObject.getString("weipicSamp5"));
            weightPicturesSamplingBo.setWeipicSamp6(jsonObject.getString("weipicSamp6"));
            weightPicturesSamplingBo.setWeipicSamp7(jsonObject.getString("weipicSamp7"));
            weightPicturesSamplingBo.setWeipicSamp8(jsonObject.getString("weipicSamp8"));
            weightPicturesSamplingBo.setWeipicSamp9(jsonObject.getString("weipicSamp9"));
            weightPicturesSamplingBo.setWeipicSamp10(jsonObject.getString("weipicSamp10"));
            weightPicturesSamplingBo.setSampWght(jsonObject.getString("sampWght"));
// 检查至少有一个图片字段非空
            boolean hasImage =
                    !isEmpty(weightPicturesSamplingBo.getWeipicSamp1()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp2()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp3()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp4()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp5()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp6()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp7()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp8()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp9()) ||
                            !isEmpty(weightPicturesSamplingBo.getWeipicSamp10());

            if (hasImage) {
                weightSheetsBu.samplingUpload(weightPicturesSamplingBo);
                samplingBu.unloadConfirm(weightSheetNo,jsonObject.getString("sampWght"));
            }
            if (enterTime != null) {
                samplingBu.enterConfirm(coalYardAreaId, weightSheetNo, enterUserId, enterTime);
            }
            if (outTime != null) {
                samplingBu.outConfirm(weightSheetNo, outUserId, outTime);
            }
        }
        return SzResult.Success();
        }catch (Exception e){
            System.out.println("提交失败，后台报错,请重新选择图片视频");
            e.printStackTrace();
            return SzResult.Error("提交失败，后台报错,请重新选择图片视频");
        }
    }

    // 辅助方法：检查字符串是否为空或null
    private static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    @PostMapping("/videoUpload")
    public ResponseEntity<?> uploadVideo(
            @RequestParam String sheetNo,
            @RequestParam MultipartFile video)  {
        // 1. 增强文件验证
        if (video.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择有效的视频文件");
        }

        // 验证文件类型
        String contentType = video.getContentType();
        if (!Arrays.asList("video/mp4", "video/quicktime", "video/x-msvideo").contains(contentType)) {
            return ResponseEntity.badRequest().body("仅支持MP4、MOV、AVI格式的视频");
        }

        // 2. 创建按日期分类的存储目录
        String dateFolder = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        Path uploadPath = Paths.get("samplingVideos", dateFolder);

        try {
            Files.createDirectories(uploadPath);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("服务器存储空间错误");
        }

        // 3. 生成安全的文件名
        String originalFilename = StringUtils.cleanPath(Objects.requireNonNull(video.getOriginalFilename()));
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = sheetNo + "_" + System.currentTimeMillis() + fileExtension;
        Path filePath = uploadPath.resolve(filename);

        // 4. 保存文件（带MD5校验）
        try {
            // 计算文件MD5
            String md5 = DigestUtils.md5DigestAsHex(video.getInputStream());

            // 保存文件
            Files.copy(video.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 验证文件完整性
            if (!md5.equals(DigestUtils.md5DigestAsHex(Files.newInputStream(filePath)))) {
                Files.deleteIfExists(filePath);
                return ResponseEntity.status(500).body("文件校验失败，请重新上传");
            }


//            weightSheetsBu.uploadVideoPath(sheetNo, relativePath);

//将文件最终地址放到数据库
            weightSheetsBu.uploadVideoPath( sheetNo, dateFolder + "/" + filename);
// 6. 构造响应
            Map<String, Object> result = new HashMap<>();
            result.put("videoUrl", "/api/videos/" + dateFolder + "/" + filename);
            result.put("fileSize", video.getSize());
            result.put("md5", md5);
            result.put("sheetNo", sheetNo);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "上传成功");
            response.put("result", result);

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            e.printStackTrace();
            try {
                Files.deleteIfExists(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            return ResponseEntity.status(500).body("文件处理失败: " + e.getMessage());
        }
    }

//    每天22点半


    // 视频访问接口
//    @GetMapping("/videos/{filename:.+}")
//    public ResponseEntity<Resource> serveVideo(@PathVariable String filename) {
//        try {
//            Path filePath = Paths.get(uploadDir).resolve(filename);
//            Resource resource = new UrlResource(filePath.toUri());
//
//            if (resource.exists() || resource.isReadable()) {
//                return ResponseEntity.ok()
//                        .header(HttpHeaders.CONTENT_TYPE, "video/mp4")
//                        .body(resource);
//            } else {
//                return ResponseEntity.notFound().build();
//            }
//        } catch (Exception e) {
//            return ResponseEntity.status(500).build();
//        }
//    }

//    根据单号获取图片
    @PostMapping("/getSamplingImgAndDetail")
    public SzResult getSamplingImgAndDetail(@RequestBody JSONObject jsonObject) {

            String weipicSheetno = jsonObject.getString("weipicSheetno");

         return   samplingBu.getSamplingImgAndDetail(weipicSheetno);

    }


    @GetMapping(value = "/video", produces = "video/mp4")
    public ResponseEntity<StreamingResponseBody> video(
            @RequestParam("weishtSheetno") String weishtSheetno,
            HttpServletRequest request) {

        // 1. 查询和验证逻辑
        CWeightPicturesSampling cWeightPicturesSampling = cWeightPicturesSamplingMapper.selectWeipicSamp11BySheetNo(weishtSheetno);
        if (cWeightPicturesSampling == null) {
            return ResponseEntity.notFound().build();
        }

        Path filePath = Paths.get("samplingVideos").resolve(cWeightPicturesSampling.getWeipicSamp11()).normalize();
        if (!Files.exists(filePath)) {
            return ResponseEntity.notFound().build();
        }

        try {
            // 2. 准备文件信息
            long fileLength = Files.size(filePath);
            String rangeHeader = request.getHeader("Range");

            // 3. 处理范围请求
            if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
                String[] ranges = rangeHeader.substring(6).split("-");
                long start = Long.parseLong(ranges[0]);
                long end = ranges.length > 1 ? Long.parseLong(ranges[1]) : fileLength - 1;

                // 验证范围
                if (start >= fileLength) {
                    HttpHeaders headers = new HttpHeaders();
                    headers.set("Content-Range", "bytes */" + fileLength);
                    return ResponseEntity.status(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
                            .headers(headers)
                            .build();
                }

                // 范围请求响应
                return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                        .header("Content-Type", "video/mp4")
                        .header("Content-Length", String.valueOf(end - start + 1))
                        .header("Content-Range", "bytes " + start + "-" + end + "/" + fileLength)
                        .header("Accept-Ranges", "bytes")
                        .body(outputStream -> {
                            try (RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r")) {
                                file.seek(start);
                                byte[] buffer = new byte[1024 * 8];
                                long remaining = end - start + 1;

                                while (remaining > 0) {
                                    int read = file.read(buffer, 0, (int) Math.min(buffer.length, remaining));
                                    if (read == -1) break;
                                    outputStream.write(buffer, 0, read);
                                    remaining -= read;
                                }
                            }
                        });
            }

            // 4. 完整文件响应
            return ResponseEntity.ok()
                    .header("Content-Type", "video/mp4")
                    .header("Content-Length", String.valueOf(fileLength))
                    .header("Accept-Ranges", "bytes")
                    .body(outputStream -> Files.copy(filePath, outputStream));

        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

//    查询批次的所有采样重量
//public SzResult getBatchAllSamplingWeight(String weightSheetNo) {
@PostMapping("/getBatchAllSamplingWeight")
        public SzResult getBatchAllSamplingWeight(@RequestBody JSONObject jsonObject) {
        String weightSheetNo = jsonObject.getString("weightSheetNo");
        return  samplingBu.getBatchAllSamplingWeight(weightSheetNo);
        }

//            public void setValue() {
@GetMapping("/setValue")
public void setValue() {
      toEamSystem.setValue();
}

    @GetMapping("/getValue")
    public void getValue() {
        weightSheetsBu.testGetSamplingImg1BySheetNo();
    }
}


